package com.yuanqi.controller;

import com.yuanqi.domain.User;
import com.yuanqi.service.UserService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/auth")
@CrossOrigin(origins = "*")
public class AuthController {

    @Autowired
    private UserService userService;

    @Value("${jwt.secret:erp_login_secret_key}")
    private String secret;

    @Value("${jwt.expiration:86400000}")
    private long expiration;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest request) {
        try {
            // 使用数据库验证用户
            var userOpt = userService.authenticateUser(request.getUsername(), request.getPassword());

            if (userOpt.isPresent()) {
                User user = userOpt.get();
                String token = generateToken(user);

                Map<String, Object> response = new HashMap<>();
                response.put("code", 0);
                response.put("message", "登录成功");

                Map<String, Object> data = new HashMap<>();
                data.put("token", token);
                data.put("username", user.getUsername());
                data.put("name", user.getName());

                data.put("expiresIn", expiration);
                response.put("data", data);

                return ResponseEntity.ok(response);
            } else {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 401);
                response.put("message", "用户名或密码错误");
                response.put("data", null);

                return ResponseEntity.status(401).body(response);
            }
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "登录失败：" + e.getMessage());
            response.put("data", null);

            return ResponseEntity.status(500).body(response);
        }
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody RegisterRequest request) {
        try {
            User user = userService.createUser(
                request.getUsername(),
                request.getPassword(),
                request.getName()
            );

            Map<String, Object> response = new HashMap<>();
            response.put("code", 0);
            response.put("message", "注册成功");
            response.put("data", user.getUsername());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", "注册失败：" + e.getMessage());
            response.put("data", null);

            return ResponseEntity.status(400).body(response);
        }
    }

    /**
     * 临时调试接口：生成密码哈希
     */
    @PostMapping("/debug/hash")
    public ResponseEntity<?> generateHash(@RequestBody DebugHashRequest request) {
        try {
            String hash = userService.encodePassword(request.getPassword());

            Map<String, Object> response = new HashMap<>();
            response.put("code", 0);
            response.put("message", "哈希生成成功");
            response.put("data", hash);

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "哈希生成失败：" + e.getMessage());
            response.put("data", null);

            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 生成JWT token
     */
    private String generateToken(User user) {
        try {
            Date now = new Date();
            Date expiryDate = new Date(now.getTime() + expiration);

            // 使用HS256算法，或者生成足够强的密钥
            // 方案1：使用HS256算法（推荐，更安全且兼容）
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] keyBytes = md.digest(secret.getBytes(StandardCharsets.UTF_8));
            SecretKey key = Keys.hmacShaKeyFor(keyBytes);

            return Jwts.builder()
                    .setSubject(user.getUsername())
                    .claim("username", user.getUsername())
                    .claim("userId", user.getId())
                    .claim("name", user.getName())
                    .setIssuedAt(now)
                    .setExpiration(expiryDate)
                    .signWith(key, SignatureAlgorithm.HS256)  // 改为HS256
                    .compact();
        } catch (Exception e) {
            throw new RuntimeException("生成JWT token失败: " + e.getMessage(), e);
        }
    }

    public static class LoginRequest {
        private String username;
        private String password;

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }
    }

    public static class RegisterRequest {
        private String username;
        private String password;
        private String name;

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    public static class DebugHashRequest {
        private String password;

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }
    }


}


